<template>
    <el-dialog title="JSON Schema" :visible.sync="dialogVisible" append-to-body width="800px" @opened="initEditor">
        <div class="monaco-dialog-editor-container">
            <div class="container-header">
                <el-button id="copy" class="jsonschema-btn" @click="clickCopy">
                    <span role="img" class="appIcon">
                        <svg-icon icon-class="copy" width="16" height="16" />
                    </span>
                    {{ $t("tool.modelManage.copyCode") }}
                </el-button>
            </div>

            <div ref="editorContainer" :class="['monaco-dialog-editor']"></div>
        </div>

        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
import * as monaco from 'monaco-editor';
import clipboard from 'clipboard'
export default {
    props: {
        jsonSchemaData: String,
        language: { type: String, default: 'json' },
        theme: { type: String, default: 'vs-dark' },

    },
    components: {
        clipboard
    },
    data() {
        return {
            dialogVisible: false,
            editor: null,
            customTheme: {
                "dark": {
                    base: 'vs-dark',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#191a23',
                    }
                },
                "darkblue": {
                    base: 'vs-dark',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#22272e',
                    }
                },
                "grey": {
                    base: 'vs-dark',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#242424',
                    }
                },
                "light": {
                    base: 'vs',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#ffffff',
                    }
                },
                "lightbrown": {
                    base: 'vs',
                    inherit: true,
                    rules: [],
                    colors: {
                        'editor.background': '#f9f4e7',
                    }
                },
            }
        };
    },
    methods: {
        openDialog() {
            this.dialogVisible = true;
            // 销毁旧实例
            if (this.editor) this.editor.dispose();
        },
        initEditor() {
            // 获取主题
            let { backKeyWord, themeConfig } = this.getSystemThemeStyle()
            // 注册主题
            monaco.editor.defineTheme(backKeyWord, themeConfig);
            // 应用主题
            monaco.editor.setTheme(backKeyWord);
            this.editor = monaco.editor.create(this.$refs.editorContainer, {
                value: this.jsonSchemaData || '',
                language: this.language,
                // theme: this.theme,
                wordWrap: 'off',
                renderLineHighlight: 'none',
                minimap: { enabled: false },
                fontSize: 12,
                lineHeight: 16,
                automaticLayout: true  // 关键：启用自动布局
            });

            // 内容同步
            this.editor.onDidChangeModelContent(() => {
                console.log("监听到内容变化");
                // this.$emit('input', this.editor.getValue());
            });

            // 窗口尺寸监听（需配合CSS）
            new ResizeObserver(() => this.editor.layout()).observe(this.$refs.editorContainer);
        },
        handleConfirm() {
            this.$emit('confirm', this.editor.getValue());
            this.dialogVisible = false;
        },
        clickCopy() {
            let _this = this;
            //创建出来的的剪贴板对象,通过id来创建剪贴对象，也可以通过class来获取剪贴对象
            let clipboardBean = new clipboard("#copy", {
                text: function (trigger) {
                    return _this.editor.getValue();
                }
            });
            clipboardBean.on('success', function (e) {
                _this.$message.success(
                    _this.$toolHandle.getI18nName(
                        _this.$zh.setup.copyText,
                        _this.$en.setup.copyText,
                        _this.$i18n.locale,
                        "success"
                    )
                );
                //复制完成后销毁clipboard对象，预防下一次调用会多次提示
                clipboardBean.destroy()
            });

            clipboardBean.on('error', function (e) {
                _this.$message.error(
                    _this.$toolHandle.getI18nName(
                        _this.$zh.setup.copyText,
                        _this.$en.setup.copyText,
                        _this.$i18n.locale,
                        "error"
                    )
                );
                //复制完成后销毁clipboard对象，预防下一次调用会多次提示
                clipboardBean.destroy()
            });
        },
        // 获取当前系统主题样式
        getSystemThemeStyle() {
            let themeConfig = localStorage.getItem("themeConfig")
            let backKeyWord = themeConfig.slice(0, themeConfig.search(/[A-Z]/));
            return {
                backKeyWord,
                themeConfig: this.customTheme[backKeyWord]
            }
        }
    },
    beforeDestroy() {
        this.editor?.dispose();
    }
};
</script>

<style scoped>
.monaco-dialog-editor {
    /* 视窗高度自适应 */
    /* border: 1px solid #dcdfe6; */
    height: 350px;
    border-radius: 4px;
}

.monaco-dialog-editor-container {
    border: 1px solid var(--ui-border-color-base);
    border-radius: 8px;
}

.container-header {
    display: flex;
    justify-content: flex-end;
    height: 38px;
    border-bottom: 1px solid var(--ui-border-color-base);
    padding: 5px 10px 5px;
}
</style>